package com.dreamstations.changshads.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import com.dreamstations.changshads.util.L;

/**
 * Created by QYH on 2016/5/12.
 * 通用的BottomBar
 * 对外提供选定项改变的接口
 * 内部对选定项做
 */
public class BottomBar extends LinearLayout {
    private static final String TAG = BottomBar.class.getName();
    private int lastSelected = 0;
    View[] views;

    //对外公布的接口，用于监听选定项目的变化
    OnBottomItemChangeListener onBottomItemChangeListener;

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (onBottomItemChangeListener == null) {
                L.i(TAG,"onBottomItemChangeListener have not init");
                return;
            }
            int select = -1;
            select= (int) v.getTag();
            if (select == -1 || select == lastSelected) return;
            //改变选定状态
            views[lastSelected].setSelected(false);
            views[select].setSelected(true);

            lastSelected = select;
            L.i(TAG,"select:"+select);
            //回调通知HomeActivity
            onBottomItemChangeListener.onSelectedItemChanged(select);
        }
    };

    public BottomBar(Context context) {
        this(context, null);
    }

    public BottomBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        final int childCount;
        childCount=getChildCount();
        L.i(TAG,"childCount:"+String.valueOf(childCount));

        views=new View[childCount];
        for (int i=0;i<childCount;i++){
            View v=getChildAt(i);
            v.setTag(i);
            views[i]=v;
            v.setOnClickListener(onClickListener);
        }

        views[0].setSelected(true);
    }

    public void setOnBottomItemChangeListener(OnBottomItemChangeListener onBottomItemChangeListener){
        this.onBottomItemChangeListener=onBottomItemChangeListener;
    }

    public interface OnBottomItemChangeListener {
        void onSelectedItemChanged(int selected);
    }
}
